<template>
    <div
        class="page_root"
        :key="queryUpdateFlag"
        data-page-name="市场占有率分析"
        data-page-identification="z_c06tfrygrs"
    >
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_alrw8ri7qx 面包屑_826y6allnc -->
            <a-breadcrumb class="vid_alrw8ri7qx" style="word-break: break-word">
                <a-breadcrumb-item
                    v-for="(item, index) in vid_alrw8ri7qx_props_tabConfig"
                    :key="index"
                    @click="handleBreadcrumbJump(router, item)"
                    href=""
                >
                    <template v-if="vid_alrw8ri7qx_props.rt_showIcon">
                        <span v-if="/^(https?:|mailto:|tel:|data:image)/.test(item.icon)" role="img" class="anticon"
                            ><embed style="width: 1em; height: 1em" :src="item.icon"
                        /></span>
                        <component v-else :is="item.icon" />
                    </template>
                    {{ item.title }}
                </a-breadcrumb-item>
            </a-breadcrumb>
            <!-- end vid_alrw8ri7qx 面包屑_826y6allnc -->
            <!-- begin vid_x5evdsd5xf 自定义模板_x6epeaj6d6 -->
            <a-spin :spinning="state.spinng" tip="加载中...">
                <div class="body">
                    <div class="top-search">
                        <div>
                            <a-row :gutter="24">
                                <a-col :span="5">
                                    <a-form-item label="省份">
                                        <a-select
                                            show-search
                                            :options="state.provinceList"
                                            :field-names="{ label: 'name', value: 'id' }"
                                            :filterOption="
                                                (input, option) => {
                                                    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                            v-model:value="state.proviceId"
                                            placeholder="请选择省份"
                                            @change="changeProvice"
                                            @focus="getProvinceList(false)"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="5">
                                    <a-form-item label="地级市" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                        <a-select
                                            allow-clear
                                            v-model:value="state.cityName"
                                            placeholder="请选择地级市"
                                            :options="state.regionList"
                                            :field-names="{ label: 'name', value: 'id' }"
                                            :filterOption="
                                                (input, option) => {
                                                    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                            @focus="getRegionList"
                                            @change="getData"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="5">
                                    <a-form-item label="日期范围" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                        <a-range-picker
                                            v-model:value="state.date"
                                            value-format="YYYY-MM"
                                            format="YYYY/MM"
                                            :disabledDate="disabledDate"
                                            :allowClear="false"
                                            @change="getData()"
                                            picker="month"
                                        />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </div>
                    </div>

                    <div class="content">
                        <div class="right">
                            <div class="content-title">
                                <div class="tip">
                                    <div class="tip-msg">市场占有率分析</div>
                                </div>
                            </div>
                            <div class="chart" ref="chartContainer"> </div>
                        </div>

                        <div class="default-table">
                            <a-table
                                :scroll="{ y: 200 }"
                                :pagination="false"
                                :columns="columns"
                                :data-source="state.dynamicData"
                                bordered
                            >
                                <template #bodyCell="{ column, record, text, index }">
                                    <template v-if="column.dataIndex === 'count'">
                                        {{ index + 1 }}
                                    </template>
                                    <template v-if="column.dataIndex === 'opration'">
                                        <a-space>
                                            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                                            <a-popconfirm @confirm="handleDelete(record)" title="确定删除吗？">
                                                <a-button type="link">删除</a-button>
                                            </a-popconfirm>
                                        </a-space>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                    </div>
                </div>
            </a-spin>
            <!-- end vid_x5evdsd5xf 自定义模板_x6epeaj6d6 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    const vid_alrw8ri7qx_props = reactive({
        rt_showIcon: false
    })

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */
    const vid_alrw8ri7qx_props_tabConfig = computed(() => {
        const initValue = [
            {
                'key': 'tab1',
                'title': '数据分析',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'icon': '',
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            },
            {
                'key': 'tab2',
                'title': '市场占有率分析',
                'icon': '',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            }
        ]
        return initValue
    })
    /*** PUBLISH_EXEGESIS ***
 systemStore.addBreadcrumbInfo(vid_alrw8ri7qx_props_tabConfig.value);
 *** PUBLISH_EXEGESIS ***/
    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import { nextTick } from 'vue'
    import * as echarts from 'echarts'
    // 定制化逻辑
    const state = reactive({
        proviceId: undefined,
        regionList: [],
        cityName: undefined,
        groupList: [],
        provinceList: [],
        date: [],
        dynamicData: [],
        urlRegionId: undefined,
        urlProviceId: undefined,
        spinng: undefined
    })

    // 获取省份
    function getProvinceList(flag) {
        get(`/dynamic-price/api/v1/compete_price_and_market_share/province  `).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            state.provinceList = data.data
            if (flag) {
                // state.proviceId = state.provinceList[0].id
                let proviceName = state.provinceList.find(item => item.name == '吉林省')
                state.proviceId = proviceName.id
            }
            if (flag) {
                getData()
            }
        })
    }
    function getRegionList() {
        get(`/dynamic-price/api/v1/region_info/city/${state.proviceId}`).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            state.regionList = data.data
        })
    }
    const chartContainer = ref(null)
    let myChart = null

    // 模拟的动态数据

    // 预设的 8 种颜色
    const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4']

    // 函数：根据动态数据生成 x 轴和 series 数据
    const getOptionFromData = data => {
        const months = [...new Set(data.map(item => item.month))]
        const seriesData = {}

        data.forEach(item => {
            if (!seriesData[item.name]) {
                seriesData[item.name] = Array(months.length).fill(null)
            }
            const monthIndex = months.indexOf(item.month)
            seriesData[item.name][monthIndex] = item.share
        })

        const series = Object.keys(seriesData).map(name => ({
            name,
            type: 'line',
            data: seriesData[name].map(value => (value === null ? null : value)) // 保持 null
        }))

        console.log(series)
        return {
            xAxis: {
                type: 'category',
                data: months, // x 轴数据
                axisLine: { onZero: true },
                splitLine: { show: false }
            },
            yAxis: {
                name: '市占率：%',
                type: 'value'
            },
            grid: {
                bottom: '10%'
            },
            series,
            tooltip: {
                trigger: 'axis',
                position: function (point, params, dom, rect, size) {
                    // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
                    // 提示框位置
                    var x = 0 // x坐标位置
                    var y = 0 // y坐标位置

                    // 当前鼠标位置
                    var pointX = point[0]
                    var pointY = point[1]

                    // 外层div大小
                    // var viewWidth = size.viewSize[0];
                    // var viewHeight = size.viewSize[1];

                    // 提示框大小
                    var boxWidth = size.contentSize[0]
                    var boxHeight = size.contentSize[1]

                    // boxWidth > pointX 说明鼠标左边放不下提示框
                    if (boxWidth > pointX) {
                        x = 5
                    } else {
                        // 左边放的下
                        x = pointX - boxWidth
                    }

                    // boxHeight > pointY 说明鼠标上边放不下提示框
                    if (boxHeight > pointY) {
                        y = 5
                    } else {
                        // 上边放得下
                        y = pointY - boxHeight
                    }

                    return [x, y]
                }
            },
            legend: {
                icon: 'rect',
                data: series,
                itemWidth: 20, // 设置宽度
                itemHeight: 10, // 设置高度
                itemGap: 30, // 设置间距
                type: 'scroll',
                orient: 'horizontal',
                pageButtonPosition: 'end'
            }
        }
    }
    function changeProvice() {
        state.cityName = undefined
        getData()
    }
    function getData() {
        state.spinng = true
        const params = {
            'provinceId': state.proviceId,
            'provinceName': '',
            'cityId': state.cityName,
            'cityName': '',
            'startTime': state.date[0],
            'endTime': state.date[1]
        }
        let pName = state.provinceList.find(item => item.id === state.proviceId)
        let cName = state.regionList.find(item => item.id === state.cityName)
        if (pName) {
            params.provinceName = pName.name
        }
        if (cName) {
            params.cityName = cName.name
        }
        post('/dynamic-price/api/v1/market_share/analysis', params)
            .then(data => {
                if (data.status !== 'success') {
                    message.error(data.errorMsg)
                    return
                }
                state.dynamicData = data.data
                renderChart()
            })
            .finally(() => {
                state.spinng = false
            })
    }
    // 渲染图表函数
    const renderChart = () => {
        if (state.dynamicData.length > 0) {
            echarts.dispose(chartContainer.value)
            echarts.dispose(chartContainer.value)
            myChart = echarts.init(chartContainer.value)
            const option = getOptionFromData(state.dynamicData)
            option && myChart.setOption(option)
        } else {
            echarts.dispose(chartContainer.value)
        }
    }
    const disabledDate = current => {
        const start = dayjs(state.date[0])
        const maxEnd = start.add(6, 'month')
        return current && (current.isBefore(start) || current.isAfter(maxEnd))
    }
    onMounted(async () => {
        state.date = [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().format('YYYY-MM')]
        getProvinceList(true)
        await nextTick()

        // 初始化 ECharts 实例
        myChart = echarts.init(chartContainer.value)

        // 监听窗口尺寸变化
        window.addEventListener('resize', handleResize)
    })

    const handleResize = () => {
        if (myChart) {
            myChart.resize()
        }
    }

    // 组件卸载时移除 resize 监听器
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize)
    })
    const columns = [
        {
            title: '企业',
            align: 'center',
            dataIndex: 'name'
        },
        {
            title: '月份',
            align: 'center',
            dataIndex: 'month'
        },
        {
            title: '市占率%',
            align: 'center',
            dataIndex: 'share'
        }
    ]
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .vid_alrw8ri7qx :deep(a) {
        color: undefined;
    }
    :deep(.vid_alrw8ri7qx.@{ant-prefix}-breadcrumb) > span:last-child a {
        color: undefined;
        opacity: 0.75;
    }
    .vid_alrw8ri7qx {
        height: 40px;
        display: flex;
        align-items: center;
        flex-wrap: undefined;
        margin-bottom: 24px;
        padding-right: 24px;
        padding-left: 24px;
        background-color: #ffffff;
    }

    .body {
        padding: 0 24px;
    }

    .page_root {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    .top-search {
        height: 68px;
        background-color: #fff;
        padding: 16px 24px;
        border-radius: 4px;
        margin-bottom: 16px;
    }

    .content {
        background-color: #fff;
        border-radius: 4px;
        padding: 24px;
        padding-top: 24px;
        height: calc(100vh - 180px);
        padding-bottom: 8px;
    }

    .chart {
        margin-bottom: 20px;
        height: 300px;
    }

    /*表格按钮通用样式*/
    .default-table :deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #f5f5f5;
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 600;
        color: #262626;
        padding: 8px 16px;
    }

    .default-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 6px 16px;
        word-break: break-all;
    }

    /*表格按钮通用样式*/
    .right {
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    }
    .content-title {
        padding: 10px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .tip {
        height: 40px;
        display: flex;
        line-height: 20px;
        align-items: center;
    }
    .tip-msg {
        height: 20px;
        font-size: 16px;
        line-height: 20px;
        font-weight: 600;
    }
</style>
